package cn.jsony.basic.controller;

import cn.jsony.basic.util.AjaxResult;
import cn.jsony.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/*
* 上传and删除
* */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传接口：
     * @RequestPart("file") - 此file要与前端文件上传组【elementUi】件的name属性值一致
     * @param file
     * @return
     */
    @RequestMapping
    public AjaxResult fastDfs(@RequestPart("file")MultipartFile file){
        try {
            //获取文件原始名
            String originalFilename = file.getOriginalFilename(); //xxx.png
            //获取扩展名
            String exName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//png
            //调用工具类上传到fastDIs
            String fileName = FastDfsUtils.upload(file.getBytes(), exName);
            //将文件名响应给前端
            return AjaxResult.me().setResultObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 文件删除接口
     *  /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg = path
     *  group1   M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
     * @return
     */
    @DeleteMapping                      //path：k，v形式对应的
    public AjaxResult delete(@RequestParam("path") String path){
        try {
            // /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg

            String pathTemp = path.substring(1);// group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            //获取组名
            String pathGroup = pathTemp.substring(0, pathTemp.indexOf("/"));
            //获取文件名
            String pathFile = pathTemp.substring(pathTemp.indexOf("/") + 1);
            //执行方法
            FastDfsUtils.delete(pathGroup,pathFile);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }

    }
}
